
import axios, { AxiosError } from "axios";
import router from "@/router";

import type { AxiosRequestConfig } from "axios";

 
import { ElLoading, ElMessage } from "element-plus";

  
export const httpInstance = axios.create()


export type BkResponest = {
    data: any;
    code: number;
    msg: string;
}


httpInstance.defaults.baseURL = import.meta.env.VITE_BASEURL;


export const $http = async (config: AxiosRequestConfig) => {
   const loadingInstance =  ElLoading.service();
    try {

        const axiosResponse = await httpInstance<BkResponest>(config);

        const bkResponest = axiosResponse.data


        if (bkResponest.code === 0 && bkResponest.msg === 'NOT_LOGIN') {
            let errorTitle: string = 'Error';
            console.log('用户为登录, 直接跳转至登录页面');
            // 重定向
            router.replace('/login');
            
            const err = new Error(bkResponest?.msg || '没有登陆')
            err.name = errorTitle // 设置错误的名字为错误标题  
            throw err // 抛出这个错误对象  
        }
   
        return bkResponest;
    } catch (err) {
        if (err instanceof AxiosError) {
            console.error('Axios error:', err);
            ElMessage.error('网络错误')
        } else {
            console.error('Unknown error:', err);
            ElMessage.error('未知错误')
        }
        throw err;  
    }finally {
        loadingInstance.close();
    }
}